package com.wzx.web.controller.system.user;

import com.github.pagehelper.PageInfo;
import com.wzx.domain.Result;
import com.wzx.domain.system.dept.Dept;
import com.wzx.domain.system.module.Module;
import com.wzx.domain.system.role.Role;
import com.wzx.domain.system.user.User;
import com.wzx.service.system.dept.IDeptService;
import com.wzx.service.system.module.IModuleService;
import com.wzx.service.system.role.IRoleService;
import com.wzx.service.system.user.IUserService;
import com.wzx.web.controller.BaseController;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/system/user")
public class UserController extends BaseController {
    private static  final Logger l = LoggerFactory.getLogger(UserController.class);

    @Autowired
    IUserService iUserService;
    @Autowired
    IDeptService iDeptService;

    @RequestMapping(path="/toList",method ={ RequestMethod.GET, RequestMethod.POST})
    public String toList(@RequestParam(defaultValue = "1") int curr, @RequestParam(defaultValue = "10")int pageSize){
        //调查询分页列表的方法
        PageInfo<User> pi = iUserService.findByPage(curr, pageSize,getLoginCompanyId());
        //将pi添加到页面
        request.setAttribute("pi",pi);
        return "system/user/user-list";
    }

    // var url= '${path}/system/user/delete.do?userId='+id;
    //  var fn = function(result){ //{code:200,msg:'删除成功',data:null}
    @RequestMapping(path="/delete",method ={ RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    Object delete(String userId){//参数接收页面js提交过来的userId
        boolean flag = iUserService.deleteUser(userId);
        if(flag){
            return Result.init(200,"删除成功",null);
        }else{
            return Result.init(-200,"删除失败",null);
        }
    }



    @RequestMapping(path="/toAdd",method ={ RequestMethod.GET, RequestMethod.POST})
    public String toAdd(){
        //页面上有一个下拉菜单 ，需要查询所有的部门
        List<Dept> depts = iDeptService.findAll(getLoginCompanyId());
        //添加到request
        request.setAttribute("depts",depts);
        return "system/user/user-add";
    }
  //  ${path}/system/user/add.do
    @RequestMapping(path="/add",method ={ RequestMethod.GET, RequestMethod.POST})
    public String add(User user){//接收页面提交过来的表单数据
        l.info("add user="+user);

        //用户或者员工属于一家公司，所以公司companyId是必须的
        user.setCompanyId(getLoginCompanyId());
        user.setCompanyName(getLoginCompanyName());

        l.info("add user="+user);

        iUserService.saveUser(user);


        return "redirect:/system/user/toList.do";
    }
    //${path}/system/user/toUpdate.do?userId=${o.userId}
    @RequestMapping(path="/toUpdate",method ={ RequestMethod.GET, RequestMethod.POST})
    public String toUpdate(String userId){//需要使用参数接收提交的 userId
        l.info("toUpdate userId="+userId);
        //需要根据userId查询当前模块的记录，回显

        User user =  iUserService.findUserById(userId);
        l.info("toUpdate user="+user);
        request.setAttribute("user",user);
        //页面上有一个下拉菜单 ，需要查询所有的部门
        List<Dept> depts = iDeptService.findAll(getLoginCompanyId());
        //添加到request
        request.setAttribute("depts",depts);
        return "system/user/user-update";
    }

    //${path}/system/user/update.do
    @RequestMapping(path = "/update", method = {RequestMethod.GET, RequestMethod.POST})
    public String update(User user) {//需要接收编辑页面提交的表单数据
        l.info("update user=" + user);
        //更新
        iUserService.updateUser(user);
        return "redirect:/system/user/toList.do";
    }

    @Autowired
    IRoleService iRoleService;
    @RequestMapping(path = "/toUserRole", method = {RequestMethod.GET, RequestMethod.POST})
    public String toUserRole(String userId){
        //接收页面传过来的userId
        l.info("toUserRole userId="+userId);
        //使用userId查找用户对象
        User user = iUserService.findUserById(userId);
        //转发给页面
        request.setAttribute("user",user);

        //所有角色的数据
        String companyId=getLoginCompanyId();
        List<Role> roleList =  iRoleService.findAll(companyId);
        //老王的角色数据
        List<Role> userRoleList =  iRoleService.findRolesByUserId(userId);
        l.info("toUserRole roleList = "+roleList);
        l.info("toUserRole userRoleList = "+userRoleList);

        for(Role role: roleList){
            //当前公司的所有的角色
            if(isInUserRoleList(role,userRoleList)){
                role.setChecked(true);
            }
        }
        //转发到页面
        request.setAttribute("roleList",roleList);
        request.setAttribute("userRoleList",userRoleList);
        return "system/user/user-role";
    }

    //当前的复选框 要不要打勾 取决于是否在 用户的角色列表中
    private boolean isInUserRoleList(Role role, List<Role> userRoleList) {
        for( Role r:userRoleList){
            if(r.getRoleId().equals(role.getRoleId())){
                return true;
            }
        }//end for
        return false;
    }

    //${path}/system/user/updateUserRole.do
    //userId
    //String[] roleIds
    @RequestMapping(path = "/updateUserRole", method = {RequestMethod.GET, RequestMethod.POST})
    public String updateUserRole(String userId,String[] roleIds){//接收用户的userId与角色的roleIds
        //String userId="002108e2-9a10-4510-9683-8d8fd1d374ef";
        //String[] roleIds = {"4028a1cd4ee2d9d6014ee2df4c6a0010"};
        l.info("updateUserRole userId = "+userId);
        l.info("updateUserRole roleIds = "+ Arrays.toString(roleIds));
        //用户的角色修改
        iRoleService.updateUserRole(userId,roleIds);
        //打开列表页面
        return "redirect:/system/user/toList.do";
    }

     //${path}/system/user/login.do
     //email
    //password
    @Autowired
    IModuleService iModuleService;
    @RequestMapping(path = "/login", method = {RequestMethod.GET, RequestMethod.POST})
    public String login(String email,String password){
        //根据 email查询对应的用户
        l.info("login email "+email);
        l.info("login password "+password);
        User user = iUserService.findUserByEmail(email);
        l.info("login user "+user);
        if (user != null) {
            //1:找到
            //比较账号密码
            if(user.getPassword().equals(password)){
                //正确
                l.info("正确");
                //保存用户信息
                session.setAttribute("loginUser",user);
                //一个 Module对象 就是左侧栏上的一个菜单项
                List<Module> menus = iModuleService.findModulesByUser(user);
                session.setAttribute("menus",menus);
                l.info("login menus "+menus);
                //跳到主页
                return "redirect:/home/toMain.do";
            }else{
                //密码不对
                l.info("密码不对");
                request.setAttribute("error","邮箱或者密码不对");
                return "forward:/login.jsp";
            }
        }else{
            //2:没找到
            //用户不存在
            l.info("用户不存在");
            request.setAttribute("error","用户不存在");
            return "forward:/login.jsp";
        }
    }

    @RequestMapping(path = "/loginOut", method = {RequestMethod.GET, RequestMethod.POST})
    public String loginOut(){
        //删除session中的用户信息
        session.removeAttribute("loginUser");
        //让session过期
        session.invalidate();
        return "redirect:/login.jsp";//转发不会改地址的数据，只有重定向会
    }

    //${path}/system/user/login-shiro.do
    @RequestMapping(path = "/login-shiro", method = {RequestMethod.GET, RequestMethod.POST})
    public String loginShiro(String email,String password) {
        //根据 email查询对应的用户
        l.info("loginShiro email " + email);
        l.info("loginShiro password " + password);
        //使用shiro框架进行认证  结果也是三种可能  正确 没有异常，用户不存在 UnknownAccountException，密码出错 IncorrectCredentialsException
        //本质是需要调用realm进行查找用户
        Subject subject = SecurityUtils.getSubject();//获取连接
        //1:先获取subject 表示对securitymanager连接
        //2:调用 securitymanager
        //3:再调用realm
        //难验信息
        UsernamePasswordToken token = new UsernamePasswordToken(email, password);//身份验证
        try {
            subject.login(token);//正确  --realm
            //正确
            l.info("正确");
            //保存用户信息
            //要求访问realm返回一个user对象
            User user = (User) subject.getPrincipal();//  --realm
            session.setAttribute("loginUser",user);
            //一个 Module对象 就是左侧栏上的一个菜单项
            List<Module> menus = iModuleService.findModulesByUser(user);
            session.setAttribute("menus",menus);
            l.info("login menus "+menus);
            //跳到主页
            return "redirect:/home/toMain.do";
        } catch (UnknownAccountException e) {//用户不存在
            e.printStackTrace();
            l.info("用户不存在");
            request.setAttribute("error","用户不存在");
            return "forward:/login-shiro.jsp";
        }catch (IncorrectCredentialsException e){//密码出错
            e.printStackTrace();
            l.info("密码不对");
            request.setAttribute("error","邮箱或者密码不对");
            return "forward:/login-shiro.jsp";
        }


    }

    @RequestMapping(path = "/loginOut-shiro", method = {RequestMethod.GET, RequestMethod.POST})
    public String loginOutShiro(){
        //删除session中的用户信息
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login-shiro.jsp";
    }
}
